<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use EasyWeChat\Foundation\Application;

use App\User;

class WxController  extends Controller
{

	public $app = null;

	public function __construct(){
		$options = [
			'debug' => true,
			'app_id' => 'wxccd4ba8c98e3d52a',
			'secret' => 'd4624c36b6795d1d99dcf0547af5443d',
			'token' => 'shifu203',
			// 'aes_key' => null, //  可选
			'log' => [
				'level' => 'debug',
				'file' => '/data/www/fenxiao/easywechat.log', //  绝对路径！！！！
				],
			//...
			];

		$this->app = new Application($options);
	}


	public function index(){

		$server = $this->app->server;
		$server->setMessageHandler(function($message){

			if($message->MsgType == 'event'){
				return $this->shijian($message);
			}elseif ($message->MsgType == 'text') {
				return $this->message();
			}
		});

		$server->serve()->send();

	}




	public function shijian($message){
		$userModel = new User();

		$openid = $message->FromUserName;

		if($message->Event == 'subscribe'){

			$userservice = $this->app->user;
			$userinfo = $userservice->get($openid);
			$name = $userinfo->nickname;

			$Quser = $userModel->where('openid',$openid)->first();
			if($Quser){
				$Quser->status = 1;
				$Quser->save();
			}else{
				// 设置带参数的二维码
				if($message->EventKey){
					$p1_openid = str_replace('qrscene_','',$message->EventKey);
					// 查询 , 修改
					$p1_user = $userModel->where('openid',$p1_openid)->first();
					// 写入三级关系数据
					$userModel->p1 = $p1_user->uid;
					$userModel->p2 = $p1_user->p1;
					$userModel->p3 = $p1_user->p2;
				}

				$userModel->name = $name;
				$userModel->openid = $openid;
				$userModel->subtime = time();
				$userModel->save();
			}

			$this->qr($openid);
			return " 欢迎关注shifu204 !!!";
		}elseif($message->Event == 'unsubscribe'){

			$Quser = $userModel->where('openid',$openid)->first();
			if($Quser){
				$Quser->status = 0;
				$Quser->save();
			}
		}
	}

	public function message(){
		return " haha";
	}

	public function qr($openid){
		// 获取创建二维码实例
		$qrcode = $this->app->qrcode;
		// 创建永久二维码
		$result = $qrcode->forever($openid);
		$ticket = $result->ticket;
		// 获取二维码内容
		$url = $qrcode->url($ticket);
		$content = file_get_contents($url); //  得到二进制图片内容
		$dir = $this->mkd() . '/'.$openid.'.jpg';
		file_put_contents(public_path() . $dir , $content); //  写入文件
	}

	// 生成层次的文件夹
	public function mkd(){
		$today = date('/Y/m/d');
		if(!is_dir( public_path() . $today )){
			mkdir(public_path() . $today , 0777 ,true);
		}
		return $today;
	}

	



		
}

